package com.edu.lxshpc.config;

import com.edu.lxshpc.filter.JwtAuthenticationTokenFilter;
import com.edu.lxshpc.handler.*;
import com.edu.lxshpc.service.MyUserDetailsService;
import com.edu.lxshpc.service.impl.MyUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


/**
 * @author zgh
 * @date 2023/10/25
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfiguration {

    @Bean
    public MyUserDetailsService myUserDetailsService() {
        return new MyUserDetailsServiceImpl();
    }

    @Autowired
    private MySuccessHandler LoginSuccessHandler;
    @Autowired
    private MyFailurHandler LoginFailurHandler;
    @Autowired
    private AuthenticationExceptionHandler authenticationExceptionHandler;
    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;
    @Autowired
    private MyLogoutHandler myLogoutHandler;

    /**
     * 配置http相关设置
     *
     * @param http
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //资源认证，放行/user/请求下的
        http.authorizeHttpRequests()
                .requestMatchers("/user/**").permitAll()
                .requestMatchers("/article/**","/other/**").permitAll()
                .anyRequest()
                .authenticated();
        // 资源处理
        http.formLogin()
                .loginProcessingUrl("/user/login")
                .permitAll()
                .successHandler(LoginSuccessHandler) // 登陆成功处理器
                .failureHandler(LoginFailurHandler); // 登陆失败处理器
        http.logout().permitAll().logoutSuccessHandler(myLogoutHandler); // 注销登陆处理器
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationExceptionHandler) // 认证异常处理器
                .accessDeniedHandler(myAccessDeniedHandler); //无权限处理器
        http.addFilterBefore(new JwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //跨域关闭csrf
        http.cors()
                .and()
                .csrf()
                .disable();
        return http.build();
    }

    /**
     * 解决跨域问题
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    /**
     *
     * 自定义认证逻辑
     * @return AuthenticationProvider
     */
    @Bean
    public AuthenticationProvider authenticationProvider() {
        // 创建一个用户认证提供者
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        // 设置用户相信信息，可以从数据库中读取、或者缓存、或者配置文件
        authProvider.setUserDetailsService(myUserDetailsService());
        // 设置加密机制，若想要尝试对用户进行身份验证，我们需要知道使用的是什么编码
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;

    }

    /**
     * 自定义认证管理器
     * @param config AuthenticationConfiguration
     * @return AuthenticationManager
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    /**
     * 密码加密器
     *
     * @return BC加密器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
